import ejs from 'ejs';
import Koa from 'koa';

import fs from 'node:fs';
import path from 'node:path';



export default (app: Koa<Koa.DefaultState, Koa.DefaultContext>) => {


    app.context.view = function (...args: Array<string | Record<string, any>>) {
        let template = '';
        let resData: Record<string, any> = {};
        if (args.length === 1) {
            if (typeof args[0] === 'string') {
                template = args[0];
            } else if (typeof args[0] === 'object') {
                // 就是对象
                if (!this.reqPath.apiName) {
                    throw new Error('Strong routing functions need to specify the target rendering template');
                }
                template = path.join(this.reqPath.filePath, this.reqPath.apiName);
                if (Array.isArray(args[0])) {
                    throw new Error("You should pass an object, not an array");
                }
                resData = args[0];
            } else {
                throw new Error("When there is only one argument, this must be the object or template name string");
            }
        } else if (args.length === 2) {
            const [name, data] = args;
            if (typeof name !== 'string') throw new Error('When passing two arguments, the first argument must be the specified template, which is a string');
            template = name;
            if (typeof data !== 'object') throw new Error("When passing two arguments, the second argument must be the data to be passed to the template, which is an object");
            if (Array.isArray(data)) {
                throw new Error("You should pass an object, not an array");
            }
            resData = data
        }
        const templatePath = path.join(__dirname, '../Views/', `${template}.ejs`);
        if (!fs.existsSync(templatePath)) {
            throw new Error(`'${template}' The specified template does not exist`);
        }
        const templateContent = fs.readFileSync(templatePath, 'utf8');
        this.type = 'text/html';
        ejs.delimiter = '%'; // 设置模板分隔符
        const templateDir = path.parse(template).dir;
        return ejs.render(templateContent, resData, {
            debug: false,
            root: path.join(__dirname, '../Views/'),
            views: [path.join(__dirname, '../Views/', templateDir)],
        });
    }



    return async (ctx: Koa.Context, next: Koa.Next) => {
        await next();
    }
}
